package io.github.uicdb.badskill.api.impl;

import io.github.uicdb.badskill.SkillOption;
import io.github.uicdb.badskill.api.CostumerConsumer;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.scores.Score;

import java.util.ArrayList;
import java.util.List;

public class ScoreBoardConsumer implements CostumerConsumer {
    public static final ScoreBoardConsumer INSTANCE=new ScoreBoardConsumer();
    protected ScoreBoardConsumer(){}
    @Override
    public boolean consume(Player player, String key, double amounts, SkillOption stack, boolean simulate) {
                    return getScore(player,key)>=amounts;
    }
    private int getScore(Player player,String key){
        var sb=player.getScoreboard();
        if(sb.hasObjective(key)){
            var obj=sb.getObjective(key);
            if(obj!=null) {
                return sb.getPlayerScores(obj).stream().map(Score::getScore)
                        .reduce(0,Integer::sum);
            }
        }
        return 0;
    }

    @Override
    public boolean retreated(Player player, String key, double amounts, SkillOption stack, boolean backResources) {
        return true;
    }

    @Override
    public void enable(Player player, String key, double amounts, SkillOption stack) {

    }

    @Override
    public List<Component> getTooltips(Player player, String key, double amounts, SkillOption stack, boolean isRequirements) {
            MutableComponent keyC=Component.literal(key);
            List<Component> result=new ArrayList<>();
            var sb=player.getScoreboard();
            if(sb.hasObjective(key)){
                var obj=sb.getObjective(key);
                if(obj!=null)
                    keyC=obj.getDisplayName().copy();
            }
            keyC.withStyle(ChatFormatting.RED);
            MutableComponent amountC=Component.literal(""+ ((int)amounts))
                    .withStyle(ChatFormatting.RED);
            if(isRequirements){
                if(getScore(player,key)>=amounts) {
                    result.add(Component.translatable("tips.option.require.score", keyC, amountC).withStyle(ChatFormatting.STRIKETHROUGH));
                }
                else result.add(Component.translatable("tips.option.require.score",keyC,amountC));
            }

        return result;
    }

    @Override
    public void disable(Player player, String key, double data, SkillOption option) {

    }
}
